import React, { useEffect, useRef } from 'react';
import { Button, Form, Space, Input, message } from 'antd';
import { DownOutlined } from '#/utils/antdIcons.js';
import { TRCheckboxModal } from '@/components/index.js';
import type { ISearchFormData } from '../../type';
import { getDate } from '../../tool';
import { BaseSelect, CreaterModal, SelectAll } from '../index';
import styles from './index.less';
import moment from 'moment';

interface IProps {
  searchFormData: ISearchFormData;
  setSearchCriteriaData: (params: any) => any;
  initialValues: any;
  setMonthflashKey: any;
  setSelectFlashKey: any;
  setCheckedFlashKey: any;
  searchCriteriaData: any;
  buttonPermissions: any;
}

const SearchForm = ({
  searchFormData,
  initialValues,
  searchCriteriaData,
  setSelectFlashKey,
  setCheckedFlashKey,
  setSearchCriteriaData,
  setMonthflashKey,
  buttonPermissions,
}: IProps) => {
  const {
    marketOptions,
    dealElementOptions,
    dealElementModalOptions,
    dealElementDataObj,
    creatorOptions,
    creatorOptionsObj,
  } = searchFormData;

  const [form] = Form.useForm();
  const isFirst = useRef<boolean>(true);

  useEffect(() => {
    // console.log('initialValues', initialValues);
    // form && form.resetFields();
    // form.setFieldsValue({
    //   userList: initialValues.userList || [],
    // });
    if (isFirst.current) {
      if (initialValues.userList && initialValues.marketList && initialValues.stationList) {
        form.setFieldsValue({
          userList: initialValues.userList || [],
          marketList: initialValues.marketList || [],
          stationList: initialValues.stationList || [],
          keyWords: initialValues.keyWords,
        });
        isFirst.current = false;
      }
    } else {
      if (initialValues.userList) {
        form.setFieldsValue({
          userList: initialValues.userList || [],
        });
      }
    }
  }, [initialValues]);

  const onFinish = (data: any) => {
    const checkedDate = searchCriteriaData?.dateList
      ? searchCriteriaData?.dateList[0]
      : moment().format('YYYY-MM-DD');
    const obj = getDate(checkedDate);
    setSearchCriteriaData({
      ...data,
      dateList: obj?.dateList || [],
    });
    setSelectFlashKey(moment().valueOf());
    setMonthflashKey(moment().valueOf());
    setCheckedFlashKey(moment().valueOf());
  };

  // 点击交易单元弹出Modal框
  const handelSelectDealElement = async () => {
    let data = form.getFieldsValue()?.stationList || [];
    data = data.map((item: any) => dealElementDataObj[item]?.[0]?.value);
    const result = await TRCheckboxModal.show({
      treeData: dealElementModalOptions,
      value: data,
      title: '交易单元',
    });
    if (result.index === 1) {
      const checkedKeys = result?.checkedKeys?.map(
        (item: any) => dealElementDataObj?.[item]?.[0]?.value,
      );
      return checkedKeys;
    } else {
      return data;
    }
  };

  // 点击创建人弹出Modal框
  const handelCreatorElement = async () => {
    const data = form.getFieldsValue()?.userList || [];
    const hasSave =
      buttonPermissions?.filter((item: any) => item.menuCode === 'stationListButtonV2')?.length > 0;
    if (!hasSave) {
      message.info('请联系管理员获取相关权限');
      return data;
    } else {
      const result: any = await CreaterModal.show({
        options: creatorOptions,
        value: data,
        dataObj: creatorOptionsObj,
      });
      if (result.index === 1) {
        return result?.checkedList;
      } else {
        return data;
      }
    }
  };

  // 重置
  const onReset = () => {
    form && form.resetFields();
    const checkedDate = searchCriteriaData?.dateList
      ? searchCriteriaData?.dateList[0]
      : moment().format('YYYY-MM-DD');
    const obj = getDate(checkedDate);
    setSearchCriteriaData({
      ...initialValues,
      dateList: obj?.dateList || [],
    });
    setMonthflashKey(moment().valueOf());
    setSelectFlashKey(moment().valueOf());
    setCheckedFlashKey(moment().valueOf());
  };

  return (
    <div className={styles.container}>
      <Form
        form={form}
        name="filter"
        initialValues={initialValues}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        requiredMark={false}
        colon={false}
        labelAlign="left"
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          name="marketList"
          label="交易中心"
          rules={[{ required: true, message: '请选择交易中心' }]}
        >
          <BaseSelect
            options={marketOptions}
            maxTagCount={1}
            logo={<DownOutlined />}
            showArrow={true}
            placeholder={'请选择交易中心'}
          />
        </Form.Item>
        <Form.Item
          name="stationList"
          label="交易单元"
          rules={[{ required: true, message: '请选择交易单元' }]}
        >
          <SelectAll
            placeholder={'请选择交易单元'}
            logo={<DownOutlined />}
            showArrow={true}
            open={false}
            maxTagCount={1}
            // maxTagTextLength={10}
            onClick={handelSelectDealElement}
            options={dealElementOptions as any[]}
          />
        </Form.Item>
        <Form.Item name="keyWords" label="关键字">
          <Input placeholder="请输入关键字" />
        </Form.Item>
        <Form.Item
          name="userList"
          label="创建人"
          rules={[{ required: true, message: '请选择创建人' }]}
        >
          <SelectAll
            placeholder={'请选择创建人'}
            showArrow={true}
            open={false}
            maxTagCount={1}
            // maxTagTextLength={10}
            logo={<DownOutlined />}
            onClick={handelCreatorElement}
            options={creatorOptions as any[]}
          />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
          <Space size={'middle'}>
            <Button style={{ width: 98 }} onClick={onReset}>
              重置
            </Button>
            <Button
              style={{ width: 98 }}
              type="primary"
              htmlType="submit"
              className={styles.searchBtn}
            >
              查询
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};

export default SearchForm;
